package com.woyao;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.GetMemberResponse;
import com.woyao.core.model.Member;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;

import java.io.IOException;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;


public class MemberActivity extends AppCompatActivity {


    TextView myrole;
    TextView mytitle;
    TextView mydesc;
    CircleImageView  mysnailview ;
    Spinner statusSpinner;

    private ArrayAdapter<String> typeAdapter;
    private ArrayAdapter<String> statusAdapter;

    boolean changed = false;

    ProgressDialog progressDialog;
    Member mem =   new Member();

    Integer id = 0;

    private RadioGroup statusRadio =null;//开灯

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_member_edit);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout


        Intent intent = getIntent();
        id = intent.getIntExtra("id",0);

        this.setTitle("我的组织");

        mysnailview = (CircleImageView) findViewById(R.id.my_member_snailview);
        mytitle = (TextView)findViewById(R.id.my_member_orgtitle);
        mydesc = (TextView)findViewById(R.id.my_member_orgdesc);
        myrole = (TextView)findViewById(R.id.my_member_role);

        myrole.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("type","role");
                intent.putExtra( "content", myrole.getText() );

                intent.setClass(MemberActivity.this,  InputActivity.class);
                startActivityForResult(intent,1);
            }
        });




        statusRadio =(RadioGroup) findViewById(R.id.my_member_status);



        Button manageOrg = (Button)findViewById(R.id.manage_org);
        manageOrg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("id",mem.getOrg_id());
                intent.setClass(MemberActivity.this,  OrgActivity.class);
                startActivity(intent);
            }
        });


        Button delMem = (Button)findViewById(R.id.delete_member);
        delMem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Dialog alertDialog = new AlertDialog.Builder(MemberActivity.this).
                        setTitle("信息").
                        setMessage("删除该组织身份吗！").
                        setIcon(R.drawable.ic_launcher).
                        setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                deleteMember();
                            }
                        }).
                        setNegativeButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).
                        create();
                alertDialog.show();


            }
        });

        loadData();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        intent.putExtra("changed", changed );
        setResult(666, intent);
        finish();
        return true;
    }


    private void deleteMember(){

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在删除身份······");
        progressDialog.show();

        AsyncTask<Void, Void, BaseResponse> needTask = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall= svc.deleteMember(WoyaoooApplication.userId,id );
                try {
                    BaseResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final BaseResponse response) {
                if(response != null &&response.isSuccess()){
                    Common.alert(MemberActivity.this,"已经删除此身份");
                    Intent intent = new Intent();
                    intent.putExtra("changed", true );
                    setResult(963, intent);
                    finish();
                }
                progressDialog.dismiss();
            }
        };
        needTask.execute((Void)null);
    }

    private void loadData(){

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在获取数据······");
        progressDialog.show();

        AsyncTask<Void, Void, GetMemberResponse> needTask = new AsyncTask<Void, Void, GetMemberResponse>() {
            @Override
            protected GetMemberResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMemberResponse> responseCall= svc.getMember(WoyaoooApplication.userId,id );
                try {
                    GetMemberResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetMemberResponse response) {
                if(response != null &&response.getContent() !=null){
                    mem = response.getContent();
                    
                    renderIt();
                }
                progressDialog.dismiss();
            }
        };
        needTask.execute((Void)null);
    }

//    BusinessSelect select;
    private void renderIt(){

        mytitle.setText(mem.getTitle());
        mydesc.setText(mem.getDescription());

        if (StringUtil.notNullOrEmpty(mem.getSnailview())) {
            Picasso.with(this)
                    .load(mem.getSnailview())
                    .into(mysnailview);
        } else {
            mysnailview.setImageResource(R.drawable.no_avartar);
        }

        myrole.setText( mem.getRole());

        if (mem.getStatus().equals("ongoing")) {
            statusRadio.check(R.id.my_member_status_on);
        }else{
            statusRadio.check(R.id.my_member_status_off);
        }

        statusRadio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (checkedId == R.id.my_member_status_on){
                    Common.setMemberAttr( id,"status", "ongoing");
                }else{
                    Common.setMemberAttr( id,"status", "ever");
                }
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == 1 && resultCode == 666 ) {
            CharSequence con = data.getCharSequenceExtra("content");
            changed = true;
            myrole.setText(con);
            Common.setMemberAttr(id,"role",con.toString());
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("changed", changed );
            setResult(666, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


}
